package zb.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.applet.resources.MsgAppletViewer;
import zb.pojo.Order;
import zb.pojo.User;
import zb.service.Userservice;
import zb.util.JwtUtil;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class Usercontroller {
    @Resource
    Userservice userservice;
    @RequestMapping("/getUserById/{id}")
    //@HystrixCommand(fallbackMethod ="hystrix_show")
    public User getUserById(@PathVariable("id") Integer id)throws Exception{
//        double num=Math.random()*10;
//        System.out.println(num);
//        if(num>5){//自已造个异常情况
//            System.out.println("本地程序产生异常");
//            throw new RuntimeException("随机异常");
//        }
        return userservice.findUserById(id);

    }

//    public User hystrix_show(Integer id) throws Exception {
//        //熔断兜底
//        User user=new User();
//        user.setId(id);
//        user.setName("服务降级");
//        return user;
//    }
    @RequestMapping("/useradd")
    public Integer save(@RequestBody Order order){
        return userservice.UserAddOrder(order);
    }
    //登录
    @RequestMapping("/login")
    public Map<String,Object>login(String name){
        Map<String,Object>map=new HashMap<>();
        //调用业务
        User user = userservice.showUser(name);
        if(user.getName()!=null){
            String jwt=JwtUtil
                    .createJWT(user.getId().toString(), JSON.toJSONString(user),null);
            System.out.println("jwt:"+jwt);
            map.put("code",200);
            map.put("token",jwt);
            map.put("msg","登录成功");
        }else{
            map.put("code",401);
            map.put("token",null);
            map.put("msg","登录失败");
        }
        return map;

    }

}
